package xcmg.syn.service.order;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xcmg.syn.dao.mapper.order.MmJisoPoHeadMapper;
import xcmg.syn.dao.mapper.order.MmJisoPoLineVoteMapper;
import xcmg.syn.service.vo.order.MmJisoPoHeadVO;
import xcmg.syn.service.vo.order.MmJisoPoLineVoteVO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MmJisoPoHead 后台接口实现类
 */
@Slf4j
@Service
public class MmJisoPoHeadService {

    @Autowired
    private MmJisoPoHeadMapper mmJisoPoHeadMapper;

    @Autowired
    private MmJisoPoLineVoteMapper mmJisoPoLineVoteMapper;

    public List<MmJisoPoHeadVO> queryList(MmJisoPoHeadVO c) {
        List<MmJisoPoHeadVO> list = mmJisoPoHeadMapper.queryList(c);
        if (list == null || list.size() == 0) {
            return list;
        }
        List<Long> ids = list.stream().map(MmJisoPoHeadVO::getPoHeadId).collect(java.util.stream.Collectors.toList());
        List<MmJisoPoHeadVO> r = collectDetail(ids, list);
        return r;
    }

    private List<MmJisoPoHeadVO> collectDetail(List<Long> ids, List<MmJisoPoHeadVO> list) {
        if (ids == null || ids.size() == 0) {
            return null;
        }
        List<MmJisoPoHeadVO> rr = new ArrayList<>(list.size());
        Map<Long, List<MmJisoPoLineVoteVO>> r = new HashMap<>(ids.size());
        List<List<Long>> subIds = Lists.partition(ids, 1000);
        for (List<Long> subId : subIds) {
            doCollectDetail(subId, r);
        }
        for (MmJisoPoHeadVO m : list) {
            List<MmJisoPoLineVoteVO> dl = r.get(m.getPoHeadId());
            m.setDetailList(dl);
            rr.add(m);
        }
        return rr;
    }

    private void doCollectDetail(List<Long> ids, Map<Long, List<MmJisoPoLineVoteVO>> r) {
        MmJisoPoLineVoteVO v = new MmJisoPoLineVoteVO();
        v.setOrderIds(ids);
        List<MmJisoPoLineVoteVO> dl = mmJisoPoLineVoteMapper.queryList(v);
        if (dl == null || dl.size() == 0) {
            return;
        }
        Map<Long, List<MmJisoPoLineVoteVO>> map = dl.stream().collect(java.util.stream.Collectors.groupingBy(MmJisoPoLineVoteVO::getPoHeadId));
        r.putAll(map);
    }
}
